package svc

import (
	"dfx_cmdb/cmdb-sendmsg-rpc/internal/config"
	"dfx_cmdb/common/loadetcdconfig"
	cmdbsendmsg "dfx_cmdb/models/cmdb-sendmsg"

	toolsdatabase "gitee.com/daofeixian/dfx_golang_toolset/databases"
	toolsloadetcd "gitee.com/daofeixian/dfx_golang_toolset/loadconfig"
	toolsnosql "gitee.com/daofeixian/dfx_golang_toolset/nosqls"
	configurator "github.com/zeromicro/go-zero/core/configcenter"
	"github.com/zeromicro/go-zero/core/configcenter/subscriber"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type ServiceContext struct {
	Config         config.Config
	LoadEtcdConfig loadetcdconfig.Config
	EtcdServer     subscriber.Subscriber
	EtcdClient     configurator.Configurator[loadetcdconfig.Config]
	DB             *gorm.DB
	RC             toolsnosql.RedisClient
}

func NewServiceContext(c config.Config) *ServiceContext {
	es, ec, v := toolsloadetcd.LoadETCDConfig[loadetcdconfig.Config](c.Etcd.Hosts, c.LoadEtcdKey)

	var db *gorm.DB
	for _, v := range v.DatabasesConfig {
		if v.Name == "cmdb" {
			db = toolsdatabase.InitDBter(&v).InitDB()
		}
	}

	err := db.AutoMigrate(&cmdbsendmsg.AlterPhoneNumber{}, &cmdbsendmsg.SendMethod{}, &cmdbsendmsg.SendTemplate{}, &cmdbsendmsg.NotificationConfig{})
	if err != nil {
		logx.Error("数据库迁移失败")
		panic(err)
	}

	var rc toolsnosql.RedisClient
	for _, v := range v.RedisConfig {
		if v.Name == "cmdb" {
			rc = toolsnosql.InitNosqlter(&v).InitRedis()
		}
	}

	return &ServiceContext{
		Config:         c,
		LoadEtcdConfig: v,
		EtcdServer:     es,
		EtcdClient:     ec,
		DB:             db,
		RC:             rc,
	}
}
